"""
Hexadecimal String CRC Calculator
Version: 1.0
Author: Gavin Huang
Date: 2024-11-09

Description:
This program takes a hexadecimal string as input, converts it to a 16-bit integer array, 
calculates a CRC-16 checksum using a custom algorithm, and appends the checksum to the 
original hexadecimal string in big-endian format.

Usage:
1. Run the program.
2. Enter a hexadecimal string when prompted (e.g., "485765720001000120010000").
3. The program will output the original hexadecimal string appended with the CRC checksum in big-endian format.

Example:
Input:  "485765720001000120010000"
Output: "485765720001000120010000XXXX"  # Where XXXX is the computed CRC value in big-endian format

Note:
- Ensure the input string has an even number of hex digits for proper 16-bit grouping.
- This program assumes a custom CRC-16 calculation, designed for compatibility with specific use cases.

"""

def hex_string_to_crc(hex_str):
    # 将16进制字符串转化为16位整数数组
    buf = [int(hex_str[i:i+4], 16) for i in range(0, len(hex_str), 4)]
    
    # 计算CRC校验值
    crc_value = crc16(buf)
    
    # 将校验值转换为大端格式，并生成4位的16进制字符串
    crc_hex = f"{crc_value:04X}"
    crc_hex = crc_hex[2:] + crc_hex[:2]  # 将低位和高位字节交换以转换为大端格式
    
    # 输出原始字符串 + CRC校验值
    final_hex_str = hex_str + crc_hex
    return final_hex_str

# CRC16计算函数
def crc16(buf):
    sum_val = 0
    last = 0
    size = len(buf) * 2  # buf 中 16 位整数数量

    # 遍历 buf 进行 16 位累加
    for i in range(len(buf)):
        sum_val += buf[i]
        size -= 2

    # 如果有剩余字节，累加到总和
    if size == 1:
        last = buf[-1] & 0xFF
        sum_val += last

    # 将 32 位累加值折叠为 16 位
    sum_val = (sum_val >> 16) + (sum_val & 0xFFFF)
    sum_val += (sum_val >> 16)
    last = ~sum_val & 0xFFFF

    return last

# 从终端获取输入
hex_str = input("Enter a hex string: ").strip()
result = hex_string_to_crc(hex_str)
print("Final hex string with CRC (Big-Endian):", result)
